package com.chinadrtv.batch.admin.controller.ozing;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.chinadrtv.user.model.OzingSalesTerminal;
import com.chinadrtv.user.model.OzingSalesTerminal.Agent;
import com.chinadrtv.user.model.LabelValue;
import com.chinadrtv.user.model.OzingSalesTerminalDTO;
import com.chinadrtv.user.model.Role;
import com.chinadrtv.user.model.User;
import com.chinadrtv.user.service.ozing.OzingSalesTerminalService;
import com.chinadrtv.user.util.BeanMapper;

@Controller
public class OzingSalesTerminalController {
	
	private static ObjectMapper jsonMapper = new ObjectMapper();
		
	@Autowired
	private OzingSalesTerminalService ozingSalesTerminalService;
	    
    @RequestMapping(value = "/agent/salesterminal", method = RequestMethod.GET)
    public ModelAndView showSalesTerminal(HttpServletRequest request) {
    	OzingSalesTerminalDTO ostDTO = new OzingSalesTerminalDTO();
    	ModelMap model = new ModelMap();
    	User user = getCurrentUser(request);
    	Set<Role> roles = user.getRoles();    	
        if (roles != null) {
            for (Role role : roles) {
            	model.addAttribute("roleName", role.getName());
            }
        }    	
    	model.addAttribute("salesYearArray", ostDTO.getSalesYearArray());
        return new ModelAndView("agent/salesterminal", model);
    }
    
    @RequestMapping(value = "/agent/salesterminal/json", method = RequestMethod.GET)
    public String listSalesTerminal(@RequestParam(required = false, defaultValue = "0") int start_index,
            @RequestParam(required = false, defaultValue = "10") Integer num_per_page,
            @RequestParam(required = false) String sort,
            @RequestParam(required = false) String dir,
            String province, String city,
            String terminalName, String terminalAddress, String salesYear,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
    	User user = getCurrentUser(request);
    	Agent currentAgent = null;
    	Map<String, String> searchParaMap = new LinkedHashMap<String, String>();    	
		boolean isAdmin = false;
    	Set<Role> roles = user.getRoles();    	
        if (roles != null) {
            for (Role role : roles) {
            	if(role.getName().equals("ROLE_AGENT_ADMIN")) {
            		isAdmin = true;
            	}
            }
        }
        if(isAdmin == false){
    		String agentID = generateAgentID(user);
    		currentAgent = Agent.valueOf(agentID);
    		searchParaMap.put("province", currentAgent.getProvince());
        } else {
        	if(StringUtils.isNotBlank(province)) {
        		searchParaMap.put("province", province.trim());
        	}        	
        }
    	if(StringUtils.isNotBlank(city)) {
    		searchParaMap.put("city", city.trim());
    	}        
    	if(StringUtils.isNotBlank(terminalName)) {
    		searchParaMap.put("terminalName", terminalName.trim());
    	}
    	if(StringUtils.isNotBlank(terminalAddress)) {
    		searchParaMap.put("terminalAddress", terminalAddress.trim());
    	}
    	if(StringUtils.isNotBlank(salesYear)) {
    		searchParaMap.put("salesYear", salesYear.trim());
    	}
    	List<OzingSalesTerminalDTO> list = ozingSalesTerminalService.findOzingSalesTerminals(currentAgent, start_index, num_per_page, searchParaMap, sort, dir);    	    	
    	String jsonList = jsonMapper.writeValueAsString(list);
    	int totalRecords = ozingSalesTerminalService.findOzingSalesTerminalsCount(start_index, num_per_page, searchParaMap);
    	response.setContentType("text/json; charset=UTF-8");
        response.getWriter().print("{\"records\":" + jsonList + ",\"totalRecords\":" + totalRecords
                + ",\"startIndex\":" + start_index  + ",\"sort\":\"" + sort  + "\",\"dir\":\"" + dir + "\"}");
        response.setHeader("Cache-Control", "no-cache");
        
        return null;
    }
    
    @RequestMapping(value = "/agent/salesterminal/saveorupdate", method = RequestMethod.GET)
    public ModelAndView saveOrUpdateSalesTerminal(@RequestParam(required = true) String action, @RequestParam(required = false) String id, HttpServletRequest request) {
    	OzingSalesTerminalDTO ostDTO = null;
		User user = getCurrentUser(request);
    	Set<Role> roles = user.getRoles();    	
        if (roles != null) {
            for (Role role : roles) {
            	if(role.getName().equals("ROLE_AGENT_ADMIN")) {
            		return new ModelAndView("agent/salesterminal");
            	}
            }
        }		
		String agentID = generateAgentID(user);    	
    	if(action.equals("add")) {
    		ostDTO = new OzingSalesTerminalDTO();    		
    		ostDTO.setProvince(Agent.valueOf(agentID).getProvince());    		
    	}
    	if(action.equals("edit")) {
    		OzingSalesTerminal ost = null;
            try {
            	ost = ozingSalesTerminalService.get(Long.parseLong(id));
            } catch (ObjectRetrievalFailureException e) {
                System.out.println(e.getMessage());
            }
    		ostDTO = new OzingSalesTerminalDTO();
    		if(ost != null && ost.getAgent() != null && ost.getAgent().toString().equals(agentID)) {
        		BeanMapper.copy(ost, ostDTO);
        		ostDTO.loadEnumName();    			
    		} else {
    			action = "add";
    		}
    	}
    	ModelMap model = new ModelMap();
    	model.addAttribute("action", action);
    	model.addAttribute("ostDTO", ostDTO);
    	return new ModelAndView("agent/salesterminal_saveorupdate", model);
    }
    
    @RequestMapping(value = "/agent/salesterminal/saveorupdate", method = RequestMethod.POST)
    public String saveOrUpdateSalesTerminal(@RequestParam(required = true) String action, OzingSalesTerminalDTO ostDTO, HttpServletRequest request) {
    	Date currentDate = new Date();
    	User user = getCurrentUser(request);
    	Set<Role> roles = user.getRoles();    	
        if (roles != null) {
            for (Role role : roles) {
            	if(role.getName().equals("ROLE_AGENT_ADMIN")) {
            		return "redirect:/agent/salesterminal";
            	}
            }
        }    	
    	if(action.equals("add")) {
    		OzingSalesTerminal ost = new OzingSalesTerminal();
    		BeanMapper.copy(ostDTO, ost); 
    		ost.setDateAdded(currentDate);
    		String userName = user.getUsername();
    		ost.setCreatedBy(userName);    		
    		String agentID = generateAgentID(user);
    		Agent agent = Agent.valueOf(agentID);
    		ost.setAgent(agent);
    		ost.setProvince(agent.getProvince());
            try {
            	ozingSalesTerminalService.save(ost);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } 
    	}
    	if(action.equals("edit")) {
    		OzingSalesTerminal ost = ozingSalesTerminalService.get(ostDTO.getId());   		
    		BeanMapper.copy(ostDTO, ost);
    		ost.setLastModified(currentDate);
    		ost.setUpdateBy(user.getUsername());
            try {
            	ozingSalesTerminalService.save(ost);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }     		
    	} 	
    	return "redirect:/agent/salesterminal";
    }
    
    private User getCurrentUser(HttpServletRequest request) {
        SecurityContext ctx = (SecurityContext) request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return (User) ctx.getAuthentication().getPrincipal();
    }
    
    private String generateAgentID(User user) {
    	if (user.getSource() != null && user.getSource().equals("agent")) {
    		return "agent" + user.getSourcePk();
    	}
    	return null;
    }
	
}
